package com.xxx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxx.common.Result;
import com.xxx.entity.User;
import com.xxx.service.IUserService;
import com.xxx.utils.Jwt;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Tag(name = "TokenController", description = "token相关测试接口")
public class TokenController {
    @Autowired
    private Jwt jwt;

    @Autowired
    private IUserService userService;

    /**
     * 用户登录接口
     * @param user
     * @return
     */
    @PostMapping("/login")
    @Operation(summary = "登录搬到用户管理和卖家管理了")
    public Result login (@RequestBody User user){
        Map<String, Object> map = new HashMap<>();

        // 这里模拟通过用户名和密码，从数据库查询user

        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUserPhone,user.getUserPhone()).eq(User::getUserPassword,user.getUserPassword());
        User u = userService.getOne(lqw);
        if(u==null)
            return Result.error("手机号或密码错误");

        String token = jwt.createToken(user.getUserPhone());
        map.put("userId", u.getUserId());
        map.put("userName",u.getUserName());
        map.put("userPhone",u.getUserPhone());
        map.put("userAvatar",u.getUserAvatar());
        map.put("token",token);

        return Result.builder().data(map).build();
    }

    /**
     * 需要 Token 验证的接口
     */
    @PostMapping("/info")
    public Result info (){
        return Result.builder().code(200).build();
    }

    /**
     * 根据请求头的token获取userId
     * @param request
     * @return
     */
    @GetMapping("/getUserInfo")
    public Result getUserInfo(HttpServletRequest request){
        String usernameFromToken = jwt.getUsernameFromToken(request.getHeader("token"));
        return Result.builder().code(200).data(usernameFromToken).build();
    }

    /*
        为什么项目重启后，带着之前的token还可以访问到需要info等需要token验证的接口？
        答案：只要不过期，会一直存在，类似于redis
     */
}
